<?php
/**
 * @ClassName: Customer
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-10-31 16:01
 * @Version: V1.0.0
 */

namespace app\api\controller;

use app\common\enum\CommonEnum;
use app\common\enum\CustomerEnum;
use app\common\model;

class Customer extends Api
{
    /**
     * 客户统计
     * @return \think\response\Json
     */
    function index()
    {
        $customer_config = web_config('customer_config');
        $store_id = input('store_id', 0);
        $spread_type = input('spread_type', -1);//推广类型，-1无，1商户，2门店，3代理，4师傅，5员工

        $where = [];
        $where[] = ['c.status', '=', 1];
        $where[] = ['c.promoter', '=', $this->user_id];
        $where2 = [];

        switch ($spread_type) {
            case 1:
                // 商户
            case 2:
                // 门店
            case 4:
                // 师傅
            case 5:
                // 员工
                $where[] = ['c.spread_type', '=', $spread_type];
                $where2 = ' or cs.store_id=' . $store_id;
                $result = $this->getCountCustomers1($where, $where2, $customer_config['silent_period']);
                break;
            case 3:
                // 代理
                $where[] = ['c.spread_type', '=', $spread_type];
                $result = $this->getCountCustomers2($where, $customer_config['silent_period']);
                break;
            default:
                // 无
                $where[] = ['c.spread_type', '=', -1];
                $result = $this->getCountCustomers2($where, $customer_config['silent_period']);
                break;
        }

        return json(["code" => 1, "msg" => "获取成功", "data" => $result]);
    }

    /**
     * 客户列表
     * @return \think\response\Json
     */
    function list()
    {
        $keyword = input('keyword', '');
        $factor = input('factor', 0);
        $customer_type = input('customer_type', 0);
        $province = input('province', 0);
        $city = input('city', 0);
        $area = input('area', 0);
        $spread_type = input('spread_type', 0);
        $skip = input('skip', 0);
        $limit = input('limit', 10);

        $where[] = ['spread_type', '=', $spread_type];//推广类型
        $where[] = ['promoter', '=', $this->user_id];//推广人
        if ($keyword) {
            $where[] = ['customer_name|mobile', 'like', '%' . $keyword . '%'];
        }

        switch ($factor) {
            case 1:
                //客户类型
                if ($customer_type) {
                    $where[] = ['customer_type', '=', $customer_type];
                }
                break;
            case 2:
                //客户区域
                if ($area) {
                    $where[] = ['area', '=', $area];
                } else {
                    if ($city) {
                        $where[] = ['city', '=', $city];
                    } else {
                        if ($province) {
                            $where[] = ['province', '=', $province];
                        }
                    }
                }
                break;
            case 3:
                //客户来源
                if ($spread_type) {
                    $where[] = ['spread_type', '=', $spread_type];
                }
                break;
            default:
                //全部
                break;
        }

        $list = model\Customer::where($where)
            ->order('update_time desc')
            ->limit($skip, $limit)->select();

        foreach ($list as $k => $li) {
            $list[$k]['avatar'] = $li['avatar'] ? replace_url($li['avatar']) : replace_url('/static/images/touxiang.png');

            $ticket_where = [
                'customer_id' => $li['id'],//客户ID
                'ticket_type' => 0,//票据类型，0水票，1门票
            ];
            $list[$k]['surplus_ticket'] = model\Ticket::where($ticket_where)->where('status', 'in', [0, 1])->sum('quantity');//剩余数量
            $list[$k]['use_ticket'] = model\TicketUseHistory::where($ticket_where)->where('status', 'in', [0, 1])->sum('quantity');//使用数量

            $rack_list = model\EquipmentCustomer::where('customer_id', $li['id'])->where('status', 1)->select();
            $list[$k]['rack_list'] = $rack_list;
            $list[$k]['rack_num'] = count($rack_list);
            if ($li['regular_type'] == 2) {
                $list[$k]['week'] = CommonEnum::weeks($li['service_date']);
            } else {
                $list[$k]['week'] = '';
            }

            $grids_num = 0;
            $bucketful_num = 0;
            $empty_bucket_num = 0;
            foreach ($rack_list as $rack) {
                $grids_num = bcadd($grids_num, $rack['grids_num']);
                $bucketful_num = bcadd($bucketful_num, $rack['bucketful_num']);
                $empty_bucket_num = bcadd($empty_bucket_num, $rack['empty_bucket_num']);
            }
            $list[$k]['grids_num'] = $grids_num;
            $list[$k]['bucketful_num'] = $bucketful_num;
            $list[$k]['empty_bucket_num'] = $empty_bucket_num;
        }

        $result = [
            'data' => $list,
            'is_more' => count($list) >= $limit,
        ];

        return json(["code" => 1, "msg" => "获取成功", "data" => $result]);
    }

    private function getCountCustomers1($where, $where2, $silent_period)
    {
        $customer_list = model\Customer::alias('c')->distinct('c.id')
            ->leftJoin('customer_store cs', 'cs.customer_id=c.id')
            ->field('c.*')
            ->where($where)//->where($where2)
            ->select();
        $total_customer = count($customer_list);//总客户数

        $before_date = date('Y-m-d H:s:i', strtotime('-' . $silent_period . ' month'));
        $silent_customer = model\Customer::alias('c')->distinct('c.id')
            ->leftJoin('customer_contacts cc', 'cc.customer_id=c.id')
            ->leftJoin('member m', 'm.id=cc.member_id')
            ->leftJoin('customer_store cs', 'cs.customer_id=c.id')
            ->where('m.last_login_time', 'lt', $before_date)
            ->where($where)//->where($where2)
            ->count();//沉默客户数
        $active_customer = bcsub($total_customer, $silent_customer);//活跃客户数

        $have_shelf = 0;//有架子客户数
        foreach ($customer_list as $customer) {
            $rack_list = model\EquipmentCustomer::where('customer_id', $customer['id'])->where('status', 1)->select();
            if (count($rack_list) >= 1) {
                $have_shelf = bcadd($have_shelf, 1);
            }
        }
        $no_shelf = bcsub($total_customer, $have_shelf);//无架子客户数

        $query = model\Customer::alias('c')->distinct('c.id')->leftJoin('customer_store cs', 'cs.customer_id=c.id');
        $family_customer = $query->where($where)
            ->where('c.customer_type', CustomerEnum::customer_type_family)
            //->where($where2)
            ->count();//家庭客户
        $enterp_customer = $query->where($where)
            ->where('c.customer_type', CustomerEnum::customer_type_enterprise)
            //->where($where2)
            ->count();//企业客户
        $street_shop = $query->where($where)
            ->where('c.customer_type', CustomerEnum::customer_type_street)
            //->where($where2)
            ->count();//街边店铺

        return [
            'total_customer' => $total_customer,
            'active_customer' => $active_customer,
            'silent_customer' => $silent_customer,
            'have_shelf' => $have_shelf,
            'no_shelf' => $no_shelf,
            'family_customer' => $family_customer,
            'enterp_customer' => $enterp_customer,
            'street_shop' => $street_shop,
        ];
    }

    private function getCountCustomers2($where, $silent_period)
    {
        $customer_list = model\Customer::alias('c')->distinct('c.id')
            ->field('c.*')
            ->where($where)
            ->select();
        $total_customer = count($customer_list);//总客户数

        $before_date = date('Y-m-d H:s:i', strtotime('-' . $silent_period . ' month'));
        $silent_customer = model\Customer::alias('c')->distinct('c.id')
            ->leftJoin('customer_contacts cc', 'cc.customer_id=c.id')
            ->leftJoin('member m', 'm.id=cc.member_id')
            ->where($where)
            ->where('m.last_login_time', 'lt', $before_date)
            ->count();//沉默客户数
        $active_customer = bcsub($total_customer, $silent_customer);//活跃客户数

        $have_shelf = 0;//有架子客户数
        foreach ($customer_list as $customer) {
            $rack_list = model\EquipmentCustomer::where('customer_id', $customer['id'])->where('status', 1)->select();
            if (count($rack_list) >= 1) {
                $have_shelf = bcadd($have_shelf, 1);
            }
        }
        $no_shelf = bcsub($total_customer, $have_shelf);//无架子客户数

        $family_customer = model\Customer::alias('c')->where($where)->where('c.customer_type', CustomerEnum::customer_type_family)->count();//家庭客户
        $enterp_customer = model\Customer::alias('c')->where($where)->where('c.customer_type', CustomerEnum::customer_type_enterprise)->count();//企业客户
        $street_shop = model\Customer::alias('c')->where($where)->where('c.customer_type', CustomerEnum::customer_type_street)->count();//街边店铺

        return [
            'total_customer' => $total_customer,
            'active_customer' => $active_customer,
            'silent_customer' => $silent_customer,
            'have_shelf' => $have_shelf,
            'no_shelf' => $no_shelf,
            'family_customer' => $family_customer,
            'enterp_customer' => $enterp_customer,
            'street_shop' => $street_shop,
        ];
    }

}